package useful;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Bijective<A extends Comparable<A>,B> implements Iterable<Pair<A,B>> {
   List<Pair<A,B>> table = new ArrayList<>();
   
   public A first(B b) {
       for(Pair<A,B> p : table) 
           if (p.second().equals(b))
               return p.first();
       return null;
   }
   
   public B second(A a) {
       for(Pair<A,B> p : table) 
           if (p.first().equals(a))
               return p.second();
       return null;
   }
   
   public void put(A a, B b) {
       table.add(new Pair<>(a,b));
   }
   
   public void add(A a, B b) {
       table.add(new Pair<>(a,b));
   }

    @Override
    public Iterator<Pair<A,B>> iterator() {
        return new BiIterator<>();
    }
    
    private class BiIterator<A extends Comparable<A>,B> implements Iterator<Pair<A,B>> {
        int cursor = 0;
        @Override
        public boolean hasNext() {
            return cursor < Bijective.this.table.size();
        }
        
        @Override
        public void remove() {
            Bijective.this.table.remove(cursor--);
        }

        @Override
        public Pair<A,B> next() {
            return (Pair<A,B>) Bijective.this.table.get(cursor++);
        }
    }
    
    @Override
    public String toString() {
        return table.toString();
    }
}
